import asyncio

import httpx
from dotenv import load_dotenv
from langgraph_sdk import get_client

# supabase init
# supabase start
# http://localhost:54323
import os
import httpx
from getpass import getpass



from langgraph_sdk import get_client


async def sign_up(email: str, password: str):
    """创建新的用户账户。"""
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"{SUPABASE_URL}/auth/v1/signup",
            json={"email": email, "password": password},
            headers={"apiKey": SUPABASE_ANON_KEY},
        )
        assert response.status_code == 200
        return response.json()


async def login(email: str, password: str):
    """为现有用户获取访问令牌。"""
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"{SUPABASE_URL}/auth/v1/token?grant_type=password",
            json={
                "email": email,
                "password": password
            },
            headers={
                "apikey": SUPABASE_ANON_KEY,
                "Content-Type": "application/json"
            },
        )
        assert response.status_code == 200
        return response.json()["access_token"]

    # 以用户 1 身份登录


async def main():
    # 创建两个测试用户
    print(f"创建测试用户：{email1} 和 {email2}")
    # await sign_up(email1, password)
    # await sign_up(email2, password)
    user1_token = await login(email1, password)
    user1_client = get_client(
        url="http://localhost:2024", headers={"Authorization": f"Bearer {user1_token}"}
    )

    # 以用户 1 身份创建线程
    thread = await user1_client.threads.create()
    print(f"✅ 用户 1 创建了线程：{thread['thread_id']}")

    # 尝试不带令牌访问
    unauthenticated_client = get_client(url="http://localhost:2024")
    try:
        await unauthenticated_client.threads.create()
        print("❌ 未认证访问应该失败！")
    except Exception as e:
        print("✅ 未认证访问被阻止：", e)

    # 尝试以用户 2 身份访问用户 1 的线程
    user2_token = await login(email2, password)
    user2_client = get_client(
        url="http://localhost:2024", headers={"Authorization": f"Bearer {user2_token}"}
    )

    try:
        await user2_client.threads.get(thread["thread_id"])
        print("❌ 用户 2 不应该看到用户 1 的线程！")
    except Exception as e:
        print("✅ 用户 2 被阻止访问用户 1 的线程：", e)


if __name__ == '__main__':
    load_dotenv(override=True)
    SUPABASE_URL = os.getenv("SUPABASE_URL")
    SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_KEY")
    SUPABASE_ANON_KEY = os.getenv("SUPABASE_ANON_KEY")
    # 从命令行获取电子邮件
    email = "553847780@qq.com"
    base_email = email.split("@")
    password = "secure-password"  # 请更改此密码
    email1 = f"553847780@qq.com"
    email2 = f"hepei119@126.com"


    if not SUPABASE_URL:
        SUPABASE_URL = getpass("请输入你的 Supabase 项目 URL：")

    # 这是你的公开匿名密钥（可在客户端安全使用）
    # 不要将其与秘密服务角色密钥混淆
    SUPABASE_ANON_KEY = os.environ.get("SUPABASE_ANON_KEY")
    if not SUPABASE_ANON_KEY:
        SUPABASE_ANON_KEY = getpass("请输入你的 Supabase 公开匿名密钥：")
    asyncio.run(main())
